package fr.upmc.tep.LTree;

import java.util.ArrayList;
import java.util.List;

/**
 * This class is a simple implementation of a Tree structure, optimized for
 * lambda calculus evaluation.
 * 
 * @author Walrus
 *
 */
public class LTree {

	private LNode rootNode;
	
	/**
	 * Default constructor.
	 */
	public LTree() {
		super();
	}
	
	/**
	 * Constructor given a left node and a right node that
	 * represents the children of the root node.
	 * @param left the left node of the root element.
	 * @param right the right node of the root element.
	 */
	public LTree(LNode left, LNode right) {
		this();
		this.rootNode = new LNode("^", left, right);
	}

	/**
	 * Return the root element of the LTree.
	 * @return the root element.
	 */
	public LNode getRootNode() {
		return rootNode;
	}

	/**
	 * Sets the root element.
	 * @param rootNode the root element to set.
	 */
	public void setRootNode(LNode rootNode) {
		this.rootNode = rootNode;
	}
	
	/**
	 * Returns a string containing all the elements in a prefix order.
	 * @return the string representative of the tree.
	 */
	public String toString(){
		return toList().toString();
	}
	
	/**
	 * Returns the list of all the elements in the tree.
	 * @return a list of LNode.
	 */
	public List<LNode> toList() {
		List<LNode> list = new ArrayList<LNode>();
		walk(rootNode, list);
		return list;
	}
	
	/**
	 * Walks the tree from left to right - prefix.
	 * @param element the element to walk.
	 * @param list the list to store the elements.
	 */
	public void walk(LNode element, List<LNode> list) {
		list.add(element);
		LNode left = element.getLeftNode();
		LNode right = element.getRightNode();
		if(left != null)
			walk(left, list);
		if(right != null)
			walk(right, list);		
	}
}
